<template>
  <div class="version-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2 class="page-title">版本管理</h2>
      <p class="page-subtitle">管理系统版本信息和配置</p>
    </div>

    <!-- 模板选择卡片 -->
    <el-card class="template-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <i class="el-icon-s-tools"></i>
          <span>模板配置</span>
        </div>
      </template>
      
      <div class="template-selector">
        <label class="selector-label">选择模板：</label>
        <el-select 
          v-model="templateId" 
          placeholder="请选择模板"
          class="template-select"
          clearable
          filterable
          @change="handleTemplateChange"
        >
          <el-option
            v-for="template in templateList"
            :key="template.id"
            :label="template.title"
            :value="template.id"
          >
            <span class="option-content">
              <span class="option-title">{{ template.title }}</span>
              <span class="option-desc">{{ template.remark }}</span>
            </span>
          </el-option>
        </el-select>
      </div>
    </el-card>

    <!-- 版本信息表单 -->
    <el-card class="form-card" shadow="hover" v-loading="formLoading">
      <template #header>
        <div class="card-header">
          <i class="el-icon-edit-outline"></i>
          <span>版本信息</span>
        </div>
      </template>

      <el-form 
        ref="versionForm" 
        :model="form" 
        :rules="formRules" 
        label-width="140px"
        class="version-form"
        @submit.prevent="handleSubmit"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="版本标题" prop="title">
              <el-input 
                v-model="form.title" 
                placeholder="请输入版本标题"
                prefix-icon="el-icon-edit"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="版本状态" prop="status">
              <el-radio-group v-model="form.status" class="status-group">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.value"
                  class="status-radio"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="版本图标" prop="icon">
              <div class="icon-upload-wrapper">
                <image-upload 
                  v-model="form.icon" 
                  class="icon-uploader"
                  :show-file-list="false"
                />
                <div class="upload-tip">
                  <i class="el-icon-picture-outline"></i>
                  <span>上传版本图标</span>
                </div>
              </div>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="最低定金价格" prop="deposit">
              <el-input 
                v-model="form.deposit" 
                placeholder="请输入最低定金价格"
                prefix-icon="el-icon-money"
                clearable
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="版本描述" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea"
            :rows="4"
            placeholder="请输入版本描述信息"
            show-word-limit
            maxlength="200"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button 
            type="primary" 
            @click="handleSubmit"
            :loading="submitLoading"
            size="medium"
          >
            <i class="el-icon-check"></i>
            保存版本
          </el-button>
          
          <el-button 
            @click="handleReset"
            size="medium"
          >
            <i class="el-icon-refresh-left"></i>
            重置表单
          </el-button>
          
          <el-button 
            type="info" 
            plain
            @click="handlePreview"
            size="medium"
          >
            <i class="el-icon-view"></i>
            预览
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addVersion } from "@/api/api/rescue";
import { listTemplate } from "@/api/api/template";

/**
 * 版本管理页面组件
 * @description 用于管理系统版本信息，包括版本配置、模板选择等功能
 */
export default {
  name: "VersionManagement",
  
  /**
   * 组件数据
   * @returns {Object} 组件响应式数据
   */
  data() {
    return {
      /** @type {string} 选中的模板ID */
      templateId: '',
      
      /** @type {Array} 模板列表 */
      templateList: [],
      
      /** @type {boolean} 表单加载状态 */
      formLoading: false,
      
      /** @type {boolean} 提交加载状态 */
      submitLoading: false,
      
      /** @type {Array} 状态选项 */
      statusOptions: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' }
      ],
      
      /** @type {Object} 表单数据 */
      form: {
        title: '',
        icon: '',
        status: '1',
        remark: '',
        deposit: ''
      },
      
      /** @type {Object} 表单验证规则 */
      formRules: {
        title: [
          { required: true, message: '请输入版本标题', trigger: 'blur' },
          { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '请上传版本图标', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择版本状态', trigger: 'change' }
        ],
        deposit: [
          { required: true, message: '请输入最低定金价格', trigger: 'blur' },
          { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
        ],
        remark: [
          { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
        ]
      }
    };
  },

  /**
   * 组件创建时的钩子函数
   */
  created() {
    this.initPage();
  },

  methods: {
    /**
     * 初始化页面数据
     */
    async initPage() {
      try {
        await this.loadTemplateList();
      } catch (error) {
        this.$message.error('页面初始化失败');
        console.error('页面初始化错误:', error);
      }
    },

    /**
     * 加载模板列表
     * @returns {Promise<void>}
     */
    async loadTemplateList() {
      try {
        this.formLoading = true;
        const response = await listTemplate();
        this.templateList = response.rows || [];
      } catch (error) {
        this.$message.error('获取模板列表失败');
        throw error;
      } finally {
        this.formLoading = false;
      }
    },

    /**
     * 处理模板选择变化
     * @param {string} templateId - 选中的模板ID
     */
    handleTemplateChange(templateId) {
      if (templateId) {
        this.$message.success(`已选择模板: ${this.getTemplateTitle(templateId)}`);
      }
    },

    /**
     * 获取模板标题
     * @param {string} templateId - 模板ID
     * @returns {string} 模板标题
     */
    getTemplateTitle(templateId) {
      const template = this.templateList.find(item => item.id === templateId);
      return template ? template.title : '';
    },

    /**
     * 处理表单提交
     */
    async handleSubmit() {
      try {
        // 表单验证
        const isValid = await this.validateForm();
        if (!isValid) return;

        this.submitLoading = true;
        
        // 构建提交数据
        const submitData = {
          ...this.form,
          templateId: this.templateId
        };

        // 提交数据
        await addVersion(submitData);
        
        this.$message.success('版本保存成功');
        this.handleReset();
        
      } catch (error) {
        this.$message.error('版本保存失败');
        console.error('提交错误:', error);
      } finally {
        this.submitLoading = false;
      }
    },

    /**
     * 验证表单
     * @returns {Promise<boolean>} 验证结果
     */
    validateForm() {
      return new Promise((resolve) => {
        this.$refs.versionForm.validate((valid) => {
          if (!valid) {
            this.$message.warning('请检查表单填写');
          }
          resolve(valid);
        });
      });
    },

    /**
     * 重置表单
     */
    handleReset() {
      this.$refs.versionForm.resetFields();
      this.templateId = '';
      this.$message.info('表单已重置');
    },

    /**
     * 预览功能
     */
    handlePreview() {
      if (!this.form.title) {
        this.$message.warning('请先填写版本标题');
        return;
      }
      
      const previewData = {
        ...this.form,
        templateId: this.templateId,
        templateTitle: this.getTemplateTitle(this.templateId)
      };
      
      this.$alert(
        `<div style="text-align: left;">
          <p><strong>版本标题：</strong>${previewData.title}</p>
          <p><strong>选择模板：</strong>${previewData.templateTitle || '未选择'}</p>
          <p><strong>版本状态：</strong>${previewData.status === '1' ? '启用' : '禁用'}</p>
          <p><strong>最低定金：</strong>${previewData.deposit}元</p>
          <p><strong>版本描述：</strong>${previewData.remark || '无'}</p>
        </div>`,
        '版本信息预览',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定'
        }
      );
    }
  }
};
</script>

<style lang="scss" scoped>
.version-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);

  .page-header {
    margin-bottom: 24px;
    
    .page-title {
      margin: 0 0 8px 0;
      font-size: 28px;
      font-weight: 600;
      color: #303133;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    
    .page-subtitle {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .template-card,
  .form-card {
    margin-bottom: 24px;
    border-radius: 12px;
    border: none;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 8px 25px 0 rgba(0, 0, 0, 0.15);
      transform: translateY(-2px);
    }

    ::v-deep .el-card__header {
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      border-bottom: 1px solid #ebeef5;
      border-radius: 12px 12px 0 0;
      padding: 20px 24px;

      .card-header {
        display: flex;
        align-items: center;
        font-weight: 600;
        color: #303133;
        font-size: 16px;

        i {
          margin-right: 8px;
          color: #409eff;
          font-size: 18px;
        }
      }
    }

    ::v-deep .el-card__body {
      padding: 24px;
    }
  }

  .template-selector {
    display: flex;
    align-items: center;
    gap: 16px;

    .selector-label {
      font-weight: 500;
      color: #606266;
      white-space: nowrap;
    }

    .template-select {
      flex: 1;
      max-width: 400px;

      ::v-deep .el-input__inner {
        border-radius: 8px;
        border: 2px solid #dcdfe6;
        transition: all 0.3s ease;

        &:focus {
          border-color: #409eff;
          box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
        }
      }
    }
  }

  .option-content {
    display: flex;
    flex-direction: column;
    
    .option-title {
      font-weight: 500;
      color: #303133;
    }
    
    .option-desc {
      font-size: 12px;
      color: #909399;
      margin-top: 2px;
    }
  }

  .version-form {
    .el-form-item {
      margin-bottom: 24px;

      ::v-deep .el-form-item__label {
        font-weight: 500;
        color: #606266;
      }

      ::v-deep .el-input,
      ::v-deep .el-textarea {
        .el-input__inner,
        .el-textarea__inner {
          border-radius: 8px;
          border: 2px solid #dcdfe6;
          transition: all 0.3s ease;

          &:focus {
            border-color: #409eff;
            box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
          }
        }
      }
    }

    .status-group {
      display: flex;
      gap: 24px;

      .status-radio {
        margin-right: 0;
        
        ::v-deep .el-radio__label {
          font-weight: 500;
        }
      }
    }

    .icon-upload-wrapper {
      display: flex;
      align-items: center;
      gap: 16px;

      .upload-tip {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #909399;
        font-size: 14px;

        i {
          font-size: 16px;
        }
      }
    }

    .form-actions {
      margin-top: 32px;
      text-align: center;

      .el-button {
        margin: 0 8px;
        padding: 12px 24px;
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s ease;

        &.el-button--primary {
          background: linear-gradient(135deg, #409eff 0%, #36a3f7 100%);
          border: none;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 15px rgba(64, 158, 255, 0.3);
          }
        }

        &:not(.el-button--primary) {
          &:hover {
            transform: translateY(-1px);
          }
        }

        i {
          margin-right: 6px;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .version-container {
    padding: 16px;

    .page-header .page-title {
      font-size: 24px;
    }

    .template-selector {
      flex-direction: column;
      align-items: stretch;
      gap: 12px;

      .template-select {
        max-width: none;
      }
    }

    .version-form {
      .el-col {
        span: 24;
      }

      .status-group {
        flex-direction: column;
        gap: 12px;
      }
    }
  }
}

// 深色模式支持
@media (prefers-color-scheme: dark) {
  .version-container {
    background: #1a1a1a;

    .page-header .page-title {
      color: #ffffff;
    }

    .template-card,
    .form-card {
      background: #2d2d2d;
      
      ::v-deep .el-card__header {
        background: linear-gradient(135deg, #2d2d2d 0%, #404040 100%);
        border-bottom-color: #404040;
      }
    }
  }
}
</style>
